<?php

namespace app\model\order;

use app\base\BaseModel;
use think\model\concern\SoftDelete;

/**
 * 退款订单记录
 * 模型-OrderItemLogisticsModel
 * Class OrderItemLogisticsModel
 * @package app\model
 */
class OrderItemOutModel extends BaseModel
{

    use SoftDelete;

    protected $name = 'order_item_out';

    /**
     * 添加退款申请
     * @param $orders
     * @param $out_explain
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addOutOrder($orders, $out_explain)
    {
        $return_data = [
            'code' => 0,
            'msg' => "订单不能重复退款"
        ];
        $map = [
            'order_id' => $orders['id']
        ];
        $order_temp = $this->where($map)->find();
        if (!empty($order_temp)) {
            return $return_data;
        }
        $this->startTrans();
        $in_out_order = [
            'order_id' => $orders['id'],
            'item_ids' => serialize($orders['item_ids']),
            'out_type' => $orders['out_type'],
            'out_explain' => $out_explain,
            'out_handle_status' => 1,
            'add_time' => date("Y-m-d H:i:s")
        ];
        $ret = $this->save($in_out_order);
        if ($ret !== false) {
            $order_model = new OrderModel();
            $ret = $order_model->handleStatus($orders['id'], $orders['item_ids'], 1);
            if ($ret === true) {
                $return_data = [
                    'code' => 1,
                    'msg' => "退款申请提交成功"
                ];
                $this->commit();
                return $return_data;
            }
        }
        $this->rollback();
        $return_data = [
            'code' => 0,
            'msg' => "退款申请提交失败"
        ];
        return $return_data;
    }

    /**
     *取消退款申请
     * @param $id
     * @param $user_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancelOutOrder($id, $user_id)
    {
        $order_model = new OrderModel();
        $out_order = $this->where('id', $id)->find();
        $ret = $order_model->where(['id' => $out_order['order_id'], 'user_id' => $user_id])->field('id')->find();
        if (!isset($ret['id'])) {
            $return_data['code'] = 0;
            $return_data['msg'] = "无权撤销本次退款订单";
            return $return_data;
        }
        $item_ids = unserialize($out_order['item_ids']);
        $this->startTrans();
        $ret = $this->destroy(['id' => $id]);
        if ($ret === true) {
            $ret = $order_model->handleStatus($out_order['order_id'], $item_ids, 0, 0);
            if ($ret === false) {
                $this->rollback();
                $return_data['code'] = 0;
                $return_data['msg'] = "撤销失败";
                return $return_data;
            }
            $this->commit();
            $return_data['code'] = 1;
            $return_data['msg'] = "撤销成功";
            return $return_data;
        }
        $this->rollback();
        $return_data['code'] = 0;
        $return_data['msg'] = "撤销失败";
        return $return_data;
    }

    /**
     * 设置退款物流
     * @param $order_id
     * @param $logistics
     * @param $type
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setLogistics($order_id, $logistics, $type = '')
    {
        $map = [
            'order_id' => $order_id
        ];
        $ret = $this->handleStatus($order_id, 4, '', '');
        if ($type == 'yes') {
            $up_logistics = [
                'out_logistics' => serialize($logistics)
            ];
            $ret = $this->where($map)->update($up_logistics);
        }
        if ($ret === false) {
            $res = [
                'code' => 0,
                'msg' => "设置失败"
            ];
        } else {
            $res = [
                'code' => 1,
                'msg' => "设置成功"
            ];
        }
        return $res;
    }

    /**
     * 更新退款订单状态
     * @param $order_id
     * @param $out_handle_status
     * @param string $out_not_text
     * @param string $goods_source
     * @param string $store_id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handleStatus($order_id, $out_handle_status, $out_not_text = '', $goods_source = 'system', $store_id = 0)
    {
        $map = [
            'order_id' => $order_id
        ];
        if (!empty($store_id)) {

            $temp_map['id'] = $order_id;
            $temp_map['store_id'] = $store_id;
            $order_model_temp = new OrderModel();
            $order = $order_model_temp->where($temp_map)->field("id")->find();
            if (empty($order)) {
                $return_data['code'] = 0;
                $return_data['msg'] = "无权操作该订单";
                return $return_data;
            }
        }
        $out_order = $this->where($map)->find();
        if (empty($out_order)) {
            $return_data['code'] = 0;
            $return_data['msg'] = "退款订单不存在";
            return $return_data;
        }
        if (intval($out_handle_status) == 3 && intval($out_order['out_type']) == 1) {
            //如果仅退款  同意字后直接退款
            $out_handle_status = 5;
        }
        $item_ids = unserialize($out_order['item_ids']);
        $order_item_model = new OrderItemModel();
//        if (!empty($goods_source)) {
//            //获取对应的发货方
//            $item_ids = $order_item_model->getSystemAgency($order_id, $item_ids, $goods_source);
//        }
        $date = date("Y-m-d H:i:s");
        switch (intval($out_handle_status)) {
            case 2:
                $up_out_data = [
                    'refuse_time' => $date
                ];
                break;
            case 3:
                $up_out_data = [
                    'agree_time' => $date
                ];
                break;
            case 4:
                $up_out_data = [
                    'send_time' => $date
                ];
                break;
            case 5:
                $up_out_data = [
                    'end_time' => $date
                ];
                break;
        }
        $up_out_data['out_handle_status'] = $out_handle_status;
        if (!empty($out_not_text)) {
            $up_out_data['out_not_text'] = $out_not_text;
        }
        $this->startTrans();
        $ret = $this->where($map)->update($up_out_data);
        if ($ret !== false) {
            $order_model = new OrderModel();
            $ret = $order_model->handleStatus($out_order['order_id'], $item_ids, $out_handle_status);
            if ($ret === false) {
                $this->rollback();
                $return_data['code'] = 0;
                $return_data['msg'] = "退款订单审核失败";
                return $return_data;
            }
            if (intval($out_handle_status) == 5) {
                $order_model = new OrderModel();
                $retx = $order_model->refundOrder($order_id, $item_ids);
                $ret = $order_item_model->cancelOrderStore($order_id, $item_ids, false);
                if ($ret === false || $retx === false) {
                    $this->rollback();
                    $tip = "退款失败";
                    if ($retx == false) {
                        $tip = "商品退还入库失败";
                    }
                    $return_data['code'] = 0;
                    $return_data['msg'] = "退款订单审核失败 " . $tip;
                    return $return_data;
                }
            }
            $this->commit();
            $return_data['code'] = 1;
            $return_data['msg'] = "退款订单审核成功";
            return $return_data;
        }
        $this->rollback();
        $return_data['code'] = 0;
        $return_data['msg'] = "退款订单审核失败";
        return $return_data;
    }

    /**
     *获取退款订单数据
     * @param $order_id
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOutInfo($order_id)
    {
        $out_item = $this->where('order_id', $order_id)->find();
        $time_list = [];
        $time_list[] = [
            'desc' => "提交申请",
            'text' => $out_item['add_time'],
            'remark' => "",
        ];
        if (!empty($out_item['agree_time'])) {
            $time_list[] = [
                'desc' => "商家同意退款",
                'text' => $out_item['agree_time'],
                'remark' => "",
            ];
        }
        if (!empty($out_item['refuse_time'])) {
            $time_list[] = [
                'desc' => "商家拒绝退款",
                'text' => $out_item['refuse_time'],
                'remark' => $out_item['out_not_text'],
            ];
        }
        if (!empty($out_item['send_time'])) {
            $time_list[] = [
                'desc' => "买家寄出物品",
                'text' => $out_item['send_time'],
                'remark' => "",
            ];
        }
        if (!empty($out_item['end_time'])) {
            $time_list[] = [
                'desc' => "商家退款",
                'text' => $out_item['end_time'],
                'remark' => "",
            ];
        }
        $out_item['list'] = $time_list;
        $out_logistics = $out_item['out_logistics'];
        if (!empty($out_logistics)) {
            $out_item['out_logistics'] = unserialize($out_item['out_logistics']);
            $out_item['out_logistics_str'] = $out_item['out_logistics']['name'] . "：" . $out_item['out_logistics']['number'];
        } else {
            $out_item['out_logistics_str'] = "无需物流";
            $out_logistics = [
                'name' => '',
                'number' => '',
            ];
            $out_item['out_logistics'] = $out_logistics;
        }
        return $out_item;
    }

    /**
     * 获取退款订单状态
     * @param $id
     * @return int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getOutStatus($id)
    {
        $out_order_data = self::where('order_id', $id)->field('out_handle_status')->find();
        if (empty($out_order_data)) {
            return 0;
        }
        return $out_order_data['out_handle_status'];
    }
}
